﻿@page "/frogsoft/permission/role/user_list"
@rendermode InteractiveServer
@inject IDialogService DialogService
@inject Frogsoft.Permission.UserService userService
@using Frogsoft.Permission.ShareDtos
@using Frogsoft.Permission.Dtos
@using System.Diagnostics
@using Frogsoft.Permission.Areas.Permission.User
@attribute [Authorize(Policy = "system_permission_user")]

<PageTitle>用户管理</PageTitle>
<h3>用户列表</h3>

<div style="margin-bottom: 16px;">
    <FluentButton Appearance="Appearance.Accent" @onclick="OpenUserAddDialog">新增用户</FluentButton>
    <FluentButton Appearance="Appearance.Accent" @onclick="loadData">刷新数据</FluentButton>
</div>

<FluentDataGrid TGridItem="AppUserDto" Items="@users.data.AsQueryable()" Pagination="@pagination" AutoGenerateColumns="true" RowSize="@DataGridRowSize.Medium">
    <PropertyColumn Property="@(p => p.Id)" Sortable="true" />
    <PropertyColumn Property="@(p => p.UserName)" Sortable="true" />
    <PropertyColumn Property="@(p => p.FullName)" Sortable="true" />
    <TemplateColumn Title="操作">
        <FluentButton Appearance="Appearance.Accent" @onclick="@(() => OpenUpdateRoleDialog(context))">分配角色</FluentButton>
        <FluentButton Appearance="Appearance.Accent" @onclick="@(() => OpenUserEditDialog(context))">编辑</FluentButton>
        <FluentButton Appearance="Appearance.Accent" @onclick="@(() => ShowDeleteConfirmation(context))" Style="margin-left: 8px;">删除</FluentButton>
    </TemplateColumn>
</FluentDataGrid>
<FluentPaginator State="@pagination" />


@code {
    PaginationState pagination = new PaginationState() { ItemsPerPage = 5 };
    Result<List<AppUserDto>> users = new Result<List<AppUserDto>>(0, 0, new List<AppUserDto>());

    private async void loadData()
    {
        Debug.WriteLine(pagination.CurrentPageIndex);
        Debug.WriteLine(pagination.ItemsPerPage);
        var pageSize = pagination.ItemsPerPage == 0 ? 5 : pagination.ItemsPerPage;
        var pageIndex = pagination.CurrentPageIndex == 0 ? 1 : pagination.CurrentPageIndex;
        users = userService.GetAllPageing(pageIndex, pageSize);
        await pagination.SetTotalItemCountAsync(users.count);        
        this.StateHasChanged();
    }

    protected override async Task OnInitializedAsync()
    {   
        await pagination.SetCurrentPageIndexAsync(0);
        loadData();
    }

    private async Task OpenUpdateRoleDialog(AppUserDto user)
    {
        Debug.WriteLine($"Updating roles for user: {user.UserName}");
        var parameters = new DialogParameters<AppUserDto>
        {
            Title = $"分配角色 - {user.UserName}",
            PrimaryAction = "确定",
            PrimaryActionEnabled = true,
            SecondaryAction = "取消",
            SecondaryActionEnabled = true,
            Width = "500px",
            TrapFocus = true,
            Modal = true,
            PreventScroll = true,
            Content = user
        };
        var dialog = await DialogService.ShowDialogAsync<UpdateRole>(user,parameters);
        DialogResult? result = await dialog.Result;
        if (!result.Cancelled)
        {
            loadData(); // 刷新数据
        }
    }

    private async Task ShowDeleteConfirmation(AppUserDto user)
    {
        var content = $"确定要删除用户 {user.UserName} 吗？此操作无法撤销。";
        var confirmationDialog = await this.DialogService.ShowConfirmationAsync(
              message: content,
              primaryText: "确定",
              secondaryText: "取消",
              title: "确认?");

        var confirmationResult = await confirmationDialog.Result;
        if (!confirmationResult.Cancelled)
        {
            Debug.WriteLine($"Deleting user: {user.UserName}");
            await userService.Delete(user.UserName);
            loadData(); 
        }
    }


    private async Task OpenUserEditDialog(AppUserDto appUserDto)
    {
        Console.WriteLine("Button clicked");
        Debug.WriteLine("Open dialog centered");
        //return Task.CompletedTask;        
        DialogParameters<AppUserDto> parameters = new()
            {
            Title = $"编辑用户-{appUserDto.UserName}",
                PrimaryActionEnabled = false,                
                SecondaryActionEnabled = false,
                Width = "500px",
                TrapFocus = true,
                Modal = true,
                PreventScroll = true,
                Content = appUserDto
            };
        var dialog = await DialogService.ShowDialogAsync<UserEdit>(appUserDto, parameters);
        DialogResult? result = await dialog.Result;
    }

    // 在 @code 块中添加新增对话框的方法
    private async Task OpenUserAddDialog()
    {
        var parameters = new DialogParameters<AppUserDto>
        {
            Title = "新增用户",
            PrimaryAction = "确定",
            PrimaryActionEnabled = true,
            SecondaryAction = "取消",
            SecondaryActionEnabled = true,
            Width = "500px",
            TrapFocus = true,
            Modal = true,
            PreventScroll = true,
            Content = new AppUserDto()
        };

        var dialog = await DialogService.ShowDialogAsync<UserAdd>(parameters);
        DialogResult? result = await dialog.Result;
        if (!result.Cancelled)
        {
            loadData(); // 刷新数据
        }
    }
}
